package com.market2.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * Locally manipulate database
 */
public class DBUtil
{
	public static void initializeDataBase() throws SQLException, ClassNotFoundException, FileNotFoundException
	{
		InputStream stream = new FileInputStream(
				Globals.TestDB.SQL_SCRIPT_FILE);

		Class.forName(Globals.TestDB.DRIVER);
		Connection connection = DriverManager.getConnection(
				Globals.TestDB.URL, 
				Globals.TestDB.USER,
				Globals.TestDB.PASSWORD
		);

		importSQL(connection, stream);
		connection.close();
	}

	public static void importSQL(Connection conn, InputStream in)
			throws SQLException {
		Scanner s = new Scanner(in);
		s.useDelimiter("(;(\r)?\n)|(--\n)");
		Statement st = null;
		try {
			st = conn.createStatement();
			while (s.hasNext()) {
				String line = s.next();
				if (line.startsWith("/*!") && line.endsWith("*/")) {
					int i = line.indexOf(' ');
					line = line
							.substring(i + 1, line.length() - " */".length());
				}

				if (line.trim().length() > 0) {
					st.execute(line);
				}
			}
		} finally {
			if (st != null)
				st.close();
		}
	}
}
